package com.example.screenprojection;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

private List<String> mData;
private OnItemClickListener mListener;

// 定义接口用于处理点击事件
public interface OnItemClickListener {
        void onItemClick(int position);
}

// 构造函数，传入数据和点击事件监听器
public MyAdapter(List<String> data, OnItemClickListener listener) {
        this.mData = data;
        this.mListener = listener;
}

// 创建 ViewHolder 实例，负责绑定视图
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                            .inflate(android.R.layout.simple_list_item_1, parent, false);
        return new MyViewHolder(view);
}

// 绑定数据到视图
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.textView.setText(mData.get(position)); // 假设数据是一个字符串

        // 为每个 item 设置点击事件
        holder.itemView.setOnClickListener(v -> {
                if (mListener != null) {
                        mListener.onItemClick(position); // 调用监听器的回调方法
                }
        });
}

// 获取数据项的数量
@Override
public int getItemCount() {
        return mData.size();
}

// ViewHolder 类，用于缓存视图
public static class MyViewHolder extends RecyclerView.ViewHolder {
        TextView textView;

        public MyViewHolder(View itemView) {
                super(itemView);
                textView = itemView.findViewById(android.R.id.text1);  // 获取 item 布局中的 TextView
        }
}
}
